package com.github.phoenics.newlives.common.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 验证sign
 *
 * @author Phoenics Chow
 * on 2019年11月13日
 */
@Slf4j
public class SignUtil {
    //notify参数生成sign
    public static boolean verify(Map<String, Object> map,String keyFiledName, String privateValue) {
        String signValue = postStrMd5(map,keyFiledName,privateValue);
        if(map.get(keyFiledName)==null){
            return false;
        }
        String strVerify=map.get(keyFiledName).toString();
        return signValue != null && (signValue.equals(strVerify.toLowerCase())|| signValue.equals(strVerify.toUpperCase()));
    }

    public static String postStrMd5(Map<String, Object> map,String keyFiledName, String privateValue){
        List<String> keyList = sortByASCII(map.keySet());
        keyList.remove(keyFiledName);
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : keyList) {
            if(map.get(key)==null){
                continue;
            }
            String vv = map.get(key).toString();
            if (StringUtils.isBlank(vv)) {
                continue;
            }
            stringBuilder.append(key);
            stringBuilder.append("=");
            stringBuilder.append(vv);
            stringBuilder.append("&");
        }
        if (StringUtils.isNotBlank(privateValue)) {
            stringBuilder.append("key=");
            stringBuilder.append(privateValue);
        }
        String stringSignTemp = stringBuilder.toString();
        //log.info("=====stringSignTemp========={}", stringSignTemp);
        return SecureUtil.md5(stringSignTemp);
    }

    private static List<String> sortByASCII(Set<String> set) {
        List<String> list = new ArrayList<String>();
        list.addAll(set);
        Collections.sort(list);
        return list;
    }

}
